<template>
	<view class="content">
		<view class="card shipping-address" @click="toAddressPage" v-if="formData.delivery_method === 1">
			<template v-if="orderStore.shoppingAddress">
				<view>
					<view>
						<label class="label">
							收花人
						</label>
						<text
							style="font-weight: 700;margin-left: 12px;">{{ orderStore.shoppingAddress.recipient }}</text>
						<text style="font-weight: 700;margin-left: 12px;">{{ orderStore.shoppingAddress.phone }}</text>
					</view>
					<view style="color: #999;font-size: 14px;margin-top: 10px;">
						{{ `${orderStore.shoppingAddress.province} ${orderStore.shoppingAddress.city} ${orderStore.shoppingAddress.district} ${orderStore.shoppingAddress.details_address}` }}
					</view>
				</view>
				<view style="margin-left: 12px;">
					<uni-icons type="right"></uni-icons>
				</view>
			</template>
			<template v-else>
				<label class="label">
					收花人
				</label>
				<view class="placeholder">
					<text>
						添加收花地址
					</text>
					<uni-icons type="right"></uni-icons>
				</view>
			</template>
		</view>

		<view class="card" style="display: flex;align-items: center;">
			<label>
				订花人电话
				<uni-icons type="help"></uni-icons>
			</label>
			<uni-easyinput :inputBorder="false" :clearable="false" placeholder="请输入电话" v-model="formData.phone"
				type="number"></uni-easyinput>
			<uni-icons custom-prefix="iconfont" type="icon-phone" color="#07c484"></uni-icons>
		</view>

		<view class="card greeting-card">
			<view style="display: flex;align-items: center;justify-content: space-between;">
				<text>贺卡文字</text>
				<switch :checked="state.greetingCard" style="transform:scale(0.7) translateX(30%)"
					@change="handleSwitchGreetingCard" />
			</view>
			<view style="margin-top: 12px;">
				<uni-easyinput v-if="state.greetingCard" type="textarea" placeholder="填写祝福语,请勿填写特殊符号和表情符号(选填)"
					autoHeight trim v-model="formData.greeting_card"></uni-easyinput>
			</view>
		</view>

		<view class="card product-card">
			<view class="product-list">
				<view class="product-item" v-for="(product,index) in orderStore.products" :key="product.id">
					<image :src="getFlowerCover(product.flower.images)" class="cover"></image>
					<view class="info">
						<view class="name">{{ product.flower.name }}</view>
						<view class="price">{{ "￥" + numeral(product.flower.price).format("0.00") }}</view>
						<view class="quantity">{{ `x ${product.quantity}` }}</view>
					</view>
				</view>
			</view>
			<view class="subtotal">
				{{ `小计 ￥${numeral(subtotal).format("0.00")}` }}
			</view>
		</view>

		<view class="card">
			<uni-forms label-position="top">
				<uni-forms-item label="收货方式">
					<uni-data-checkbox v-model="formData.delivery_method" mode="tag" :localdata="deliveryMethodOption"
						@change="handleChangeDeliveryMethod"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item :label="formData.delivery_method === 1?'配送时间':'取货时间'">
					<uni-datetime-picker type="datetime" :placeholder="formData.delivery_method === 1?'立即配送':'立即取货'"
						hide-second :start="startDeliveryDate" v-model="formData.delivery_date" :disabled="isPresal" />
				</uni-forms-item>
			</uni-forms>
		</view>

		<view class="card">
			<view style="margin-bottom: 12px;">
				订单备注
			</view>
			<uni-easyinput type="textarea" placeholder="请与客服提前沟通(选填)" autoHeight trim
				v-model="formData.notes"></uni-easyinput>
		</view>

		<view class="card warn-card">
			<view class="warn-card-title">
				<uni-icons type="info-filled" color="#ee7566" :size="24"></uni-icons>
				温馨提示
			</view>
			<view class="warn-card-content">
				鲜花属于鲜活易腐类产品，花束一经包扎或发起配送后则影响二次销售。鲜花产品不支持7天无理由退换货。
			</view>
		</view>

		<view :style="{height:safeAreaBottom+60+'px'}"></view>

		<view class="footer" :style="{'paddingBottom':safeAreaBottom+'px'}">
			<text>
				实付
			</text>
			<text class="total-price">
				{{ `￥${numeral(totalPrice).format("0.00")}` }}
			</text>
			<view class="submit" @click="handleSubmit">
				提交订单
			</view>
		</view>
	</view>
</template>

<script setup>
	import numeral from 'numeral';
	import {
		computed,
		reactive,
		ref
	} from "vue"
	import {
		AddressPageMode
	} from "@/constants/index.js"
	import {
		useOrderStore
	} from "@/stores/order.js"
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		useUserStore
	} from "@/stores/user.js"
	import {
		getFlowerCover
	} from "@/utils/index.js"
	import {
		SERVER_URL
	} from "@/config/index.js"
	import dayjs from 'dayjs';

	const userStore = useUserStore()
	const orderStore = useOrderStore()

	const safeAreaBottom = ref(0)

	const toAddressPage = () => {
		let url = "/pages/user/address?mode=" + AddressPageMode.SELECT
		if (orderStore.shoppingAddress && orderStore.shoppingAddress.id) {
			url += "&selected=" + orderStore.shoppingAddress.id
		}
		uni.navigateTo({
			url
		})
	}

	const state = reactive({
		greetingCard: true
	})

	const subtotal = computed(() => {
		const total = numeral(0)

		orderStore.products.forEach((item) => {
			const price = numeral(item.quantity).multiply(item.flower.price).value()
			total.add(price)
		})

		return total.value()
	})

	const totalPrice = computed(() => {
		const total = numeral(0)

		orderStore.products.forEach((item) => {
			const price = numeral(item.quantity).multiply(item.flower.price).value()
			total.add(price)
		})

		return total.value()
	})

	const deliveryMethodOption = [{
		text: '商家配送',
		value: 1
	}, {
		text: '到店自提',
		value: 2
	}]

	const startDeliveryDate = computed(() => {
		if (orderStore.presale_delivery_date) {
			return dayjs(orderStore.presale_delivery_date).startOf("d").format("YYYY-MM-DD HH:mm:ss")
		}

		return dayjs().endOf("minute").add(30, "minute").format("YYYY-MM-DD HH:mm:ss")
	})

	const formData = reactive({
		phone: undefined,
		notes: undefined,
		greeting_card: undefined,
		delivery_method: 1,
		delivery_date: undefined
	})

	const handleSwitchGreetingCard = (e) => {
		state.greetingCard = e.detail.value
		if (!state.greetingCard) {
			formData.greeting_card = undefined
		}
	}

	const handleSubmit = () => {
		console.log(formData)
		if (formData.delivery_method === 1 && (!orderStore.shoppingAddress || !orderStore.shoppingAddress.phone)) {
			uni.showToast({
				icon: "error",
				title: "请选择配送地址"
			})
			return
		}

		if (!formData.phone) {
			uni.showToast({
				icon: "error",
				title: "请输入订购电话"
			})
			return
		}

		let data = {
			items: orderStore.products,
			customer_phone: formData.phone,
			delivery_method: formData.delivery_method,
			delivery_date: formData.delivery_date,
			greeting_card: formData.greeting_card,
			notes: formData.notes,
			subtotal: subtotal.value,
			total_price: totalPrice.value,
		}

		if (formData.delivery_method === 1) {
			data.delivery_address = orderStore.shoppingAddress
		}

		if (orderStore.presale) {
			data.presale = true
			data.presale_delivery_date = orderStore.presale_delivery_date
		}

		uni.request({
			url: SERVER_URL + '/customer/order',
			method: "POST",
			data: data,
			header: {
				"content-type": "application/json",
				"authorization": userStore.token
			},
			success: (res) => {
				if (res.statusCode === 200) {
					uni.showToast({
						title: "下单成功",
					})
					setTimeout(() => {
						uni.redirectTo({
							url: "/pages/order/detail?payment=true&id=" + res.data.id
						})
					}, 500)
				} else {
					uni.showToast({
						title: "下单失败",
						icon: "error"
					})
				}
			}
		});
	}

	const isPresal = computed(() => {
		return orderStore.presale && orderStore.presale_delivery_date && (dayjs(orderStore.presale_delivery_date) >
			dayjs())
	})

	onLoad(() => {
		const windowInfo = uni.getWindowInfo()
		safeAreaBottom.value = windowInfo.safeAreaInsets.bottom

		formData.phone = userStore.phone
		if (isPresal.value) {
			formData.delivery_date = dayjs(orderStore.presale_delivery_date)
				.startOf("d").add(8, "h").format("YYYY-MM-DD HH:mm:ss")
		}
	})
</script>

<style scoped lang="scss">
	.content {
		min-height: 100vh;
		background: #F2F6FD;
		padding: 12px;

		.card {
			border-radius: 6px;
			background-color: #fff;
			margin-bottom: 12px;
			padding: 12px;

			:deep(.uni-forms-item) {
				margin-bottom: 0;
			}
		}

		.shipping-address {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.label {
				border: 1px solid #e75d58;
				color: #e75d58;
				padding: 2px 4px;
				border-radius: 4px;
				font-size: 0.875rem;
			}

			.placeholder {
				display: flex;
				align-items: center;
				justify-content: center;
				color: #666;

				.uni-icons {
					margin-left: 2px;
					vertical-align: middle;
				}
			}
		}

		.greeting-card {
			:deep(.uni-easyinput) {
				.uni-easyinput__content {
					background-color: #ffeeee !important;
					border-color: #ffeeee !important;
				}
			}
		}

		.product-card {
			.product-list {
				.product-item {
					margin-top: 12px;
					display: flex;
					align-items: center;

					.cover {
						width: 80px;
						height: 80px;
						margin-right: 10px;
					}

					.info {
						flex: 1;
						height: 80px;
						display: flex;
						flex-direction: column;
						overflow: hidden;

						.name {
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						.price {
							margin-top: 12px;
							color: #ee0a24;
						}

						.quantity {
							font-size: 14px;
							color: #666;
							text-align: right;
						}
					}
				}
			}

			.subtotal {
				border-top: 1px solid #eeeeee;
				margin-top: 12px;
				padding-top: 12px;
				text-align: right;
				font-weight: 700;
			}
		}

		.warn-card {
			background: linear-gradient(to bottom, #fcf6f4 0%, #ffffff 100%);

			.warn-card-title {
				margin-bottom: 12px;
				display: flex;
				align-items: center;
			}

			.warn-card-content {
				color: #a2a7aa;
				font-size: 12px;
			}
		}

		.footer {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: #fff;

			.total-price {
				color: #ee0a24;
				font-size: 1.25rem;
				padding-left: 4px;
				padding-right: 12px;
			}

			.submit {
				padding: 16px 24px;
				background-color: #ee0a24;
				color: #fff;
			}
		}
	}
</style>